//
//  ViewController.m
//  连连看初
//
//  Created by administrator on 16/6/1.
//  Copyright © 2016年 mark. All rights reserved.

#import "ViewController.h"
#import "ViewController1.h"
#import "AppDelegate.h"
@interface ViewController (){
    UIView*buttonView;
    float count;
    NSTimer *timer;
    UIButton *bt;
    NSMutableArray *mutArr ;
    NSMutableArray *mutar;
    SystemSoundID sound1;
    SystemSoundID sound2;
    SystemSoundID sound3;
    SystemSoundID sound4;
    SystemSoundID sound5;SystemSoundID sound6;
    SystemSoundID sound7;SystemSoundID sound8;
    NSMutableArray *Arr;
    int aa,kk,y,width,height,space;
    NSString *x;
}
- (IBAction)btnTest:(id)sender;
@end
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    aa=[self.rak intValue];
    [self creatButton:aa];
    mutArr=[[NSMutableArray alloc]init];
    mutar=[[NSMutableArray alloc]init];
    Arr=[[NSMutableArray alloc]init];
    x=[[NSString alloc]init];
    CFBundleRef mainBundle1 = CFBundleGetMainBundle();
    CFBundleRef mainBundle2 = CFBundleGetMainBundle();
    CFBundleRef mainBundle3 = CFBundleGetMainBundle();
    CFBundleRef mainBundle4 = CFBundleGetMainBundle();
    CFBundleRef mainBundle5 = CFBundleGetMainBundle();
    CFBundleRef mainBundle6 = CFBundleGetMainBundle();
    CFBundleRef mainBundle7 = CFBundleGetMainBundle();
    CFBundleRef mainBundle8 = CFBundleGetMainBundle();
    //获得声音文件的地址，注意格式
    CFURLRef soundFileURLRef1 = CFBundleCopyResourceURL(mainBundle1, CFSTR("wrong"),
                                                        CFSTR("wav"), NULL);
    CFURLRef soundFileURLRef2 = CFBundleCopyResourceURL(mainBundle2, CFSTR("right"),
                                                        CFSTR("wav"), NULL);
    CFURLRef soundFileURLRef3 = CFBundleCopyResourceURL(mainBundle3, CFSTR("bjj"),
                                                        CFSTR("wav"), NULL);
    CFURLRef soundFileURLRef4 = CFBundleCopyResourceURL(mainBundle4, CFSTR("victory"),
                                                        CFSTR("wav"), NULL);
    CFURLRef soundFileURLRef5 = CFBundleCopyResourceURL(mainBundle5, CFSTR("failure1"),
                                                        CFSTR("wav"), NULL);
    CFURLRef soundFileURLRef6 = CFBundleCopyResourceURL(mainBundle6, CFSTR("1"),
                                                        CFSTR("mp3"), NULL);
    CFURLRef soundFileURLRef7 = CFBundleCopyResourceURL(mainBundle7, CFSTR("2"),
                                                        CFSTR("mp3"), NULL);
    CFURLRef soundFileURLRef8 = CFBundleCopyResourceURL(mainBundle8, CFSTR("3"),
                                                        CFSTR("mp3"), NULL);
    // Create a system sound object representing the sound file
    //创建系统声音对象来代替声音文件
    AudioServicesCreateSystemSoundID(soundFileURLRef1, &sound1);
    AudioServicesCreateSystemSoundID(soundFileURLRef2, &sound2);
    AudioServicesCreateSystemSoundID(soundFileURLRef3, &sound3);
    AudioServicesCreateSystemSoundID(soundFileURLRef4, &sound4);
    AudioServicesCreateSystemSoundID(soundFileURLRef5, &sound5);
    AudioServicesCreateSystemSoundID(soundFileURLRef6, &sound6);
    AudioServicesCreateSystemSoundID(soundFileURLRef7, &sound7);
    AudioServicesCreateSystemSoundID(soundFileURLRef8, &sound8);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)creatButton:(int)side{
    //创建一个n*n按钮组
    if (side==4) {
         width = 60;
         height = 60;
         space = 2;
    }else if (side==6){
        width = 50;
        height = 50;
        space = 2;
    }else if(side==8){
        width = 38;
        height = 38;
        space = 2;
    }
    UIView *contentView = [[UIView alloc] init];
    //定义该n*n按钮组的左上角坐标和宽、高
    CGRect rect = contentView.frame;
    rect.size.width = side * width + (side - 1)*space;
    rect.size.height = side * width + (side - 1)*space;
    rect.origin.x = self.view.center.x - rect.size.width/2;
    rect.origin.y = self.view.center.y - rect.size.height/2 + 20;
    contentView.frame = rect;
    [self.view addSubview:contentView];
    buttonView = contentView;//为后面游戏重新开始提供界面初始化
    //分配内存、初始化
    self.arr = [[NSMutableArray alloc] init];
    //输出初始数组
    for (int i = 0; i < side*side;  i++) {
        NSString *A=[NSString stringWithFormat:@"%d.jpg",i%(side)];
        [self.arr addObject:A];
    }
    //打乱初始数组
    for (int i = 0 ; i < side*side; i++) {
        int a = arc4random() % (side*side);
        int b = arc4random() % (side*side);
        [self.arr exchangeObjectAtIndex:a withObjectAtIndex:b];
    }
    int k=0;kk=1;
    for (int i = 0; i < side; i ++){
        for (int j = 0; j < side; j ++) {
            bt = [[UIButton alloc] init];
            bt.frame = CGRectMake(width * j + space * j,height * i + space * i,width,height);
            [contentView addSubview:bt];
            [bt setBackgroundImage:[UIImage imageNamed:[self.arr objectAtIndex:k]] forState:UIControlStateHighlighted ];
            bt.tag=kk;
           [bt setBackgroundImage:[UIImage imageNamed:@"u.jpg"] forState:UIControlStateNormal];
            NSString *title = [self.arr objectAtIndex:k];
            //将取到的值依次序赋给Button
            [bt setTitle:title forState:UIControlStateHighlighted];//高量的时候显示标题
            [bt addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
            k++;
            kk++;
        }
    }
    y=kk-(aa*aa)/2-1;//用来判断剩余button的个数；
}
-(void)click: (UIButton *)sender {
    [mutar addObject: [sender currentTitle]];
    AudioServicesPlaySystemSound(sound3);
    NSString *str = [NSString stringWithFormat:@"%ld",(long)sender.tag];
    [mutArr addObject:str];
    if ([mutar count]>1)
    {   for (int i=0; i<[mutar count]; i++)
        {
            if ((mutar[i]==mutar[i+1])&&(mutArr[i]!=mutArr[i+1])) {
                x=@"1";
                for (int j=0; j<[mutArr count];j++){
                UIButton *myButton1 = [self.view viewWithTag:[mutArr[j] intValue]];
                UIButton *myButton2 = [self.view viewWithTag:[mutArr[j+1] intValue]];
                [myButton1 removeFromSuperview];
                [myButton2 removeFromSuperview];
                AudioServicesPlaySystemSound(sound2);
                    self.warning.text=@"继续加油！";
                    [mutArr removeAllObjects];
                    [mutar removeAllObjects];
                    y--;
                }
            }
            else {
                x=@"0";
                AudioServicesPlaySystemSound(sound1);
                [mutArr removeAllObjects];[mutar removeAllObjects];
                self.warning.text=@"拿出你的超人记忆力吧！";
                }
        }
    }
    else
    {self.warning.text=@"";x=nil;}
    if (y!=0){
        if (timer ==nil) {
            timer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(fun) userInfo:nil repeats:YES];
            count = 0;
        }
    }
    else
    {
         AudioServicesPlaySystemSound(sound4);
        [timer invalidate];
        timer=nil;
        AppDelegate *del = [[UIApplication sharedApplication]delegate];
        if (aa==4) {
            double heightestScore1 = [self.labelTimer.text doubleValue];
            if (heightestScore1 < del.heightestScore1 || del.heightestScore1 == 0) {
                del.heightestScore1 = heightestScore1;
            }
        }
        if (aa==6) {
            double heightestScore2 = [self.labelTimer.text doubleValue];
            if (heightestScore2 < del.heightestScore2 || del.heightestScore2 == 0) {
                del.heightestScore2 = heightestScore2;
            }
        }
        if (aa==8) {
            double heightestScore3 = [self.labelTimer.text doubleValue];
            if (heightestScore3 < del.heightestScore3 || del.heightestScore3 == 0) {
                del.heightestScore3 = heightestScore3;
            }
        }
        double srt=[self.labelTimer.text doubleValue];
        NSString *str=[[NSString alloc]initWithFormat:@"本次用时%0.2f s",srt ];
        UIAlertController*alert=[UIAlertController alertControllerWithTitle:@"恭喜通关！" message:str preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *ok=[UIAlertAction actionWithTitle:@"返回游戏" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action){
              ViewController *vc1=(ViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"play"];
        [self presentViewController:vc1 animated:YES completion:nil];
        }];
        [alert addAction:ok];
        [self presentViewController:alert animated:YES completion:nil];
        }
    if (x!=nil)//用来判断是否连续消除。
    {
        [Arr addObject:x];
        for (int i=0; i<Arr.count; i++) {
        if ([Arr[i] isEqualToString:@"0"]) {
            [Arr removeAllObjects];
        }  else if([Arr count]>3)
        {
            if ([Arr[i] isEqualToString:@"1"]&&[Arr[i+1]isEqualToString:@"1"]&&[Arr[i+2]isEqualToString:@"1"]&&[Arr[i+3]isEqualToString:@"1"]) {
                NSLog(@"连消4次");[Arr removeAllObjects];AudioServicesPlaySystemSound(sound8);break;
            }else if ([Arr[i] isEqualToString:@"1"]&&[Arr[i+1]isEqualToString:@"1"]&&[Arr[i+2]isEqualToString:@"1"]&&[Arr[i+3]isEqualToString:@"0"]){
                [Arr removeAllObjects];break;
            }
        }
           else if([Arr count]>2)
        {
            if ([Arr[i] isEqualToString:@"1"]&&[Arr[i+1]isEqualToString:@"1"]&&[Arr[i+2]isEqualToString:@"1"]) {
                NSLog(@"连消三次");AudioServicesPlaySystemSound(sound7);break;
            }else if ([Arr[i] isEqualToString:@"1"]&&[Arr[i+1]isEqualToString:@"1"]&&[Arr[i+2]isEqualToString:@"0"]){
                [Arr removeAllObjects];break;
            }
        }else if([Arr count]>1){
            if ([Arr[i] isEqualToString:@"1"]&&[Arr[i+1]isEqualToString:@"1"])
            {
                NSLog(@"连消两次");AudioServicesPlaySystemSound(sound6);
                break;
            }
        }
        }
    }
}
-(void)fun{
    count += 0.001;
    self.labelTimer.text =[NSString stringWithFormat:@"%.2f",count];
    if (aa==4) {
        double time=[self.labelTimer.text doubleValue];
        if (time>=20.00) {
            [timer invalidate];
            timer=nil;
            AudioServicesPlaySystemSound(sound5);
            UIAlertController*alert=[UIAlertController alertControllerWithTitle:@"游戏超时！" message:@"下次努力吧!（20s内完成本关卡）" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *ok=[UIAlertAction actionWithTitle:@"不服，再来一次" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action){
                if (buttonView != nil) {
                    [buttonView removeFromSuperview];
                    [self creatButton:4];
                    self.labelTimer.text=@"0.00";
                }
            }];
            [alert addAction:ok];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
    if (aa==6) {
        double time=[self.labelTimer.text doubleValue];
        if (time>=50.00) {
            [timer invalidate];
            timer=nil;
            AudioServicesPlaySystemSound(sound5);
            UIAlertController*alert=[UIAlertController alertControllerWithTitle:@"游戏超时！" message:@"下次努力吧!（50s内完成本关卡）" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *ok=[UIAlertAction actionWithTitle:@"不服，再来一次" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action){
                if (buttonView != nil) {
                    [buttonView removeFromSuperview];
                    [self creatButton:6];
                    self.labelTimer.text=@"0.00";
                }
            }];
            [alert addAction:ok];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
    if (aa==8) {
        double time=[self.labelTimer.text doubleValue];
        if (time>=120.00) {
            [timer invalidate];
            timer=nil;
            AudioServicesPlaySystemSound(sound5);
            UIAlertController*alert=[UIAlertController alertControllerWithTitle:@"游戏超时！" message:@"下次努力吧!（120s内完成本关卡）" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *ok=[UIAlertAction actionWithTitle:@"不服，再来一次" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action){
                if (buttonView != nil) {
                    [buttonView removeFromSuperview];
                    [self creatButton:8];
                    self.labelTimer.text=@"0.00";
                }
            }];
            [alert addAction:ok];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
}
- (IBAction)btnTest:(id)sender {
            timer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(fun) userInfo:nil repeats:YES];
}
- (IBAction)back:(id)sender {
    ViewController *vc1=(ViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"play"];
    [self presentViewController:vc1 animated:YES completion:nil];
}
@end
